import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data

mnist = input_data.read_data_sets('mnist_data/', one_hot=True)
# 定义参数
learning_rate = 0.001
training_epochs = 25
batch_size = 100
display_step = 1

# 设置网络模型参数
n_hidden_1 = 256
n_hidden_2 = 256
n_input = 784
n_classes = 10

# 定义占位符
x = tf.placeholder(tf.float32, [None, n_input])
y = tf.placeholder(tf.float32, [None, n_classes])


# 创建model
def multilayer_perception(x, weights, biases):
    # hidden layer one
    layer_1 = tf.add(tf.matmul(x, weights['h1']), biases['b1'])
    layer_1 = tf.nn.relu(layer_1)
    # hidden layer two
    layer_2 = tf.add(tf.matmul(layer_1, weights['h2']), biases['b2'])
    layer_2 = tf.nn.relu(layer_2)
    # output layer
    output_layer = tf.matmul(layer_2, weights['out']) + biases['out']

    return output_layer


# 学习参数
weights = {
    'h1': tf.Variable(tf.random_normal([n_input, n_hidden_1])),
    'h2': tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2])),
    'out': tf.Variable(tf.random_normal([n_hidden_2, n_classes])),
}
biases = {
    'b1': tf.Variable(tf.random_normal([n_hidden_1])),
    'b2': tf.Variable(tf.random_normal([n_hidden_2])),
    'out': tf.Variable(tf.random_normal([n_classes])),
}

# 输出值
predict = multilayer_perception(x, weights, biases)

# 定义loss 和 优化器
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=predict, labels=y))
optimizer = tf.train.AdamOptimizer(learning_rate).minimize(cost)

init = tf.global_variables_initializer()

# 启动session
with tf.Session() as sess_save:
    # 初始化参数
    sess_save.run(tf.global_variables_initializer())
    # 启动训练循环
    for epoch in range(training_epochs):
        avg_cost = 0
        total_batch = int(mnist.train.num_examples/batch_size)
        for _ in range(total_batch):
            batch_x, batch_y = mnist.train.next_batch(batch_size)
            # 传参优化
            _, cost_result = sess_save.run([optimizer, cost], feed_dict={x: batch_x, y: batch_y})
            # 计算平均loss值
            avg_cost += cost_result/total_batch
        if epoch % display_step == 0:
            print('Epoch: ', '%04d' % (epoch + 1), 'cost: ', '{:.9f}'.format(avg_cost))

    print('Finished!')

    # 测试模型
    correct_prediction = tf.equal(tf.argmax(predict, 1), tf.argmax(y, 1))
    # 计算准确率
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
    print('Accuracy: ', accuracy.eval({x: mnist.test.images, y: mnist.test.labels}))
